package ru.romannep.pc.chopperbattle;

import java.util.ArrayList;







interface InterfacePanel {
    void log(String s);
    void startGame();
}



public class ChopperBattleConnectionToServer extends Connection {
    InterfacePanel interfacePanel;
    PlayerState state;
    String playerName;
    ArrayList<ChopperCommands> chopperCommands;

    public ChopperBattleConnectionToServer(String serverAddress, int serverPort, InterfacePanel logPanel, String name ) {
        super(serverAddress, serverPort);
        this.interfacePanel = logPanel;
        state = PlayerState.CONNECTING;
        playerName = name;
        chopperCommands = new ArrayList<ChopperCommands>();
    }
    
    public void sendChatMessage(String message){
        if (state == PlayerState.CHATTING){
            sendMessage(new NetworkMessage(MessageType.CHAT_MESSAGE, message));
        }
        
    }
    
    void processMessageWhileChatting(NetworkMessage msg) {
        switch (msg.type) {
            case CHAT_MESSAGE:
                interfacePanel.log(msg.s);
                break;
        }
        
    }

    
    void sendGameData(ArrayList<ChopperCommands> commands){
        
        //%%% надо отправить на сервер команды
        sendMessage(new NetworkMessage(MessageType.GAME_DATA, "" + commands.get(0).gameCycle, commands));
        //System.out.println("CTS sending " + commands);
        
    }
    
    @Override
    void onConnect() {
        interfacePanel.log("Connected!");
        sendMessage(new NetworkMessage(MessageType.SET_NAME, playerName));
        state = PlayerState.CHATTING;
    }

    @Override
    void incomingMessage(NetworkMessage msg) {
//        switch (state){
//            case CHATTING:
//                processMessageWhileChatting(msg);
//                break;
//        }
        switch (msg.type) {
            case CHAT_MESSAGE:
                interfacePanel.log(msg.s);
                break;
            case GAME_DATA:
                synchronized (chopperCommands) {
                    chopperCommands.addAll(msg.commands);
                }
                break;
            case START_GAME:
                interfacePanel.startGame();
                break;
                
        }
        
    }

    @Override
    void onDisconnect(Exception ex) {
        interfacePanel.log("DISCONNECT " + ex);
        state = PlayerState.CONNECTING;
    }
}
